package com.gateway.web.servlet;

import com.alibaba.fastjson.JSON;
import com.gateway.api.domain.web.ReturnInfo;
import com.gateway.service.runner.GatewayFilterRunner;
import com.gateway.service.runner.RequestContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * @Description:
 * @author: shaoyu1
 * @date: 2019/11/4 15:42
 */
@WebServlet(urlPatterns="/api/*")
public class GatewayServlet extends HttpServlet {

    @Autowired
    private GatewayFilterRunner runner;

    @Override
    public void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        runner.init(req,resp);
        try{
            runner.preRoute();
            runner.route();
            runner.postRoute();
        }catch (Throwable e){
            e.printStackTrace();
            try {
                dealErrorResponse(e);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }finally {
            RequestContext.getCurrentContext().unset();
        }
    }

    private void dealErrorResponse(Throwable e)throws Exception {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletResponse servletResponse = ctx.getResponse();
        ReturnInfo<String> result  = ReturnInfo.error("-9000000",e.getMessage());
        byte[] body = JSON.toJSONString(result).getBytes();
        ServletOutputStream outputStream = servletResponse.getOutputStream();
        outputStream.write(body);
        outputStream.flush();
    }
}
